<?php
//PDO connections
//settings for pdo

//兼容不包括pdo的php安装 - 移除,兼容性无法保证
//if(!class_exists('PDO'))include(ROOT_PATH.'/includes/pdo/PDO.class.php');


function InsertData($DB, $data, $table)
{

	$fields = "";
	$values = "";
	foreach($data as $field=>$value)
	{
		$fields .= "$field, ";
		$values .= "'$value', ";
	}
	
	$fields = substr_replace($fields, "", -2, 1);
	$values = substr_replace($values, "", -2, 1);

	$sql = "insert into $table ($fields) values ($values)";
	//echo $sql;
	$rs = $DB->query($sql) or PDO_Error($DB,$sql);
	return $DB->lastInsertId();
}

function UpData($DB, $data, $table, $keyarr)
{

	$set = "";
	foreach($data as $field=>$value)
	{
		$set .= "$field='$value', ";
	}
	$set = substr_replace($set, "", -2, 1);

	$where = "";
	foreach($keyarr as $key=>$key_value)
	{
		$where .= "$key='$key_value'";
	}
	

	$sql = "update $table set $set where $where";
	//echo $sql;
	$rs = $DB->query($sql) or PDO_Error($DB,$sql);
	return $rs;
}

function PDO_Rowcount($rs)
{
	if(!$rs)return 0;
	return count($rs->fetchAll());
}

function PDO_GetAssoc($rs)
{
	if(!$rs)return false;
	while($row = $rs->fetch())
	{
		$keys = array_keys($row);
		$key = $row[$keys[0]];
		unset($row[$keys[0]]);
		$rows[$key] = $row;
		if(count($row)<=2)$rows[$key] = $row[$keys[1]];
	}
	return $rows;
}

function PDO_Error($pdo, $sql='')
{
	echo '<pre>';
	echo "SQL Error: $sql \n";
	print_r($pdo->ErrorInfo());
	echo '</pre>';
	return 0;
}


class extPDO
{
	function __construct($dsn, $user='', $pass='')
	{
		$this->db = new PDO($dsn, $user, $pass);
	}


	function query($sql)
	{
		$rs = $this->db->query($sql) or PDO_Error($this->db, $sql);
		return $rs;
	}


	function beginTransaction()
	{
		return $this->db->beginTransaction();
	}

	function commit()
	{
		return $this->db->commit();
	}

	function rollBack()
	{
		return $this->db->rollBack();
	}

	function exec($sql)
	{
		return $this->db->exec($sql);
	}

	function lastInsertId()
	{
		return $this->db->lastInsertId();
	}


	function setAttribute($attr, $value)
	{
		return $this->db->setAttribute($attr, $value);
	}


	function InsertData($data, $table)
	{
		return InsertData($this->db, $data, $table);
	}

	function UpData($data, $table, $keyarr)
	{
		return UpData($this->db, $data, $table, $keyarr);
	}

	
}


if($dsn && count($dsn)>0)
{
	for($i=1; $i<=count($dsn); $i++)
	{
		$n = $i-1;
		if($dsn[$n]['dbtype']=='mysql')${"db$i"} = new extPDO("{$dsn[$n][dbtype]}:host={$dsn[$n][dbhost]};dbname={$dsn[$n][dbname]}", $dsn[$n]['dbuser'], $dsn[$n]['dbpass']);
		if($dsn[$n]['dbtype']=='sqlite')${"db$i"} = new extPDO("{$dsn[$n][dbtype]}:{$dsn[$n][dbname]}");
	}
	
	
	//$db1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);
	//$db1->exec("set names '$mysql_codepage'");
}

require("$ROOT_PATH/includes/page.inc.php");
?>